package com.myhouse.controller;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.myhouse.biz.DistrictService;
import com.myhouse.biz.HouseService;
import com.myhouse.biz.StreetService;
import com.myhouse.biz.TypeService;
import com.myhouse.entity.District;
import com.myhouse.entity.House;
import com.myhouse.entity.Photo;
import com.myhouse.entity.Street;
import com.myhouse.entity.Type;
import com.myhouse.entity.User;

@Controller
public class HouseController {
	
	@Resource
	private HouseService houseService;
	@Resource
	private DistrictService districtService;
	@Resource
	private StreetService streetService;
	@Resource
	private TypeService typeService;
	

	@RequestMapping("/user/house-edit")
	public String house_edit(Integer id,Model model) {
		if(id!=null) {
			House house = houseService.getByHouse(id);
			model.addAttribute("house",house);
		}
		List<District> districts = districtService.getAll();
		List<Street> streets = streetService.getAll();
		List<Type> types = typeService.getAll();
		model.addAttribute("districts", districts);
		model.addAttribute("streets", streets);
		model.addAttribute("types",types);
		model.addAttribute("id",id);
		return "house-edit";
	}
	
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(House house,Integer hid,HttpSession session,
			@RequestParam(name="housefilename",required=false)MultipartFile housefilename,HttpServletRequest request) {
		if(hid>0) {
			house.setId(hid);
			Photo photo = new Photo();
			photo.setFilename(house.getId()+".jpg");
			photo.setId(hid);
			photo.setTitle(house.getPhoto().getTitle());
			houseService.updateHouse(house,photo);
		}else {
			house.setUpdateTime(new Date());
			house.setUser((User)session.getAttribute("user"));
			System.out.println(house.getLongitude());
			Photo photo = new Photo();
			
			houseService.addHouse(house,photo);
		}
		
		if(!housefilename.isEmpty()) {
			//获取物理路径
			String path = request.getServletContext().getRealPath("/images");
			String file = path+"//"+house.getId()+".jpg";
			try {
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(housefilename.getBytes());
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "redirect:user/list";
	}
}
